'use client';

import Link from "next/link";
import { useState, useEffect } from "react";
import { useAPIClient } from '@/utils/api-client';
import { generateTestAccounts, signTransaction, TestAccount, BlockResponse } from '@/utils/crypto';

interface TransactionStatus {
  hash: string;
  from: string;
  to: string;
  value: number;
  status: 'pending' | 'confirmed' | 'failed';
  timestamp: number;
}

interface AccountBalance {
  address: string;
  balance: number;
  nonce: number;
}

export default function Home() {
  const apiClient = useAPIClient();
  
  const [serverRunning, setServerRunning] = useState<boolean | null>(null);
  const [stateRoot, setStateRoot] = useState<string>('');
  const [transactionCount, setTransactionCount] = useState<number>(10);
  const [isGenerating, setIsGenerating] = useState(false);
  const [transactions, setTransactions] = useState<TransactionStatus[]>([]);
  const [accounts, setAccounts] = useState<TestAccount[]>([]);
  const [balances, setBalances] = useState<AccountBalance[]>([]);
  const [blocks, setBlocks] = useState<BlockResponse[]>([]);
  const [nonceMap, setNonceMap] = useState<Map<string, number>>(new Map());
  const [step, setStep] = useState<'setup' | 'generating' | 'completed'>('setup');

  // 检查服务器状态
  useEffect(() => {
    const checkServer = async () => {
      const running = await apiClient.checkServerRunning();
      setServerRunning(running);
      if (running) {
        try {
          const root = await apiClient.getStateRoot();
          setStateRoot(root);
          updateBatchInfo();
        } catch (error) {
          console.error('获取状态根失败:', error);
        }
      }
    };

    // 首次立即检查一次
    checkServer();

    // 每5秒检查一次
     const intervalId: NodeJS.Timeout = setInterval(checkServer, 5000);

    // 卸载时清理定时器
    return () => clearInterval(intervalId);
  }, [apiClient]);

  // 当账户生成后且服务器运行时，初始化nonce状态
  useEffect(() => {
    if (serverRunning && accounts.length > 0) {
      initializeNonceMap();
    }
  }, [serverRunning, accounts]);

  // 生成测试账户
  useEffect(() => {
    const testAccounts = generateTestAccounts(31); // 生成1-30号账户
    setAccounts(testAccounts);
  }, []);

  // 生成随机交易
  const generateTransactions = async () => {
    if (!serverRunning) {
      alert('服务器未运行，请先启动后端服务');
      return;
    }

    setIsGenerating(true);
    setStep('generating');
    setTransactions([]);

    const newTransactions: TransactionStatus[] = [];
    
    // 在开始前先初始化所有nonce状态
    await initializeNonceMap();
    
    // 创建本次批量交易的本地nonce映射
    const localNonceMap = new Map(nonceMap);

    try {
      for (let i = 0; i < transactionCount; i++) {
        // 随机选择发送方和接收方
        const senderIndex = Math.floor(Math.random() * 9);
        let receiverIndex = Math.floor(Math.random() * 9);
        
        // 确保发送方和接收方不同
        while (receiverIndex === senderIndex) {
          receiverIndex = Math.floor(Math.random() * 9);
        }

        const sender = accounts[senderIndex];
        const receiver = accounts[receiverIndex];
        console.log("accounts:", accounts.length, accounts);

        // 使用本地nonce映射，确保在同一批次内nonce是连续的
        const currentNonce = localNonceMap.get(sender.address) || 0;
        localNonceMap.set(sender.address, currentNonce + 1);

        console.log(`交易 ${i + 1}: from ${sender.address} to ${receiver.address} 使用nonce: ${currentNonce}`);

        // 构造交易请求
        const txReq = {
          from: sender.address,
          to: receiver.address,
          value: Math.floor(Math.random() * 4) + 1, // 1-4的随机金额
          nonce: currentNonce.toString(),
        };

        // 签名交易
        const signedTx = await signTransaction(txReq, sender);

        try {
          // 发送交易
          const response = await apiClient.sendTransaction(signedTx);
          
          const txStatus: TransactionStatus = {
            hash: response.hash,
            from: signedTx.from,
            to: signedTx.to,
            value: signedTx.value,
            status: 'pending',
            timestamp: Date.now(),
          };

          newTransactions.push(txStatus);
          setTransactions([...newTransactions]);

          // 异步等待确认
          apiClient.waitForConfirmation(response.hash).then((confirmed: boolean) => {
            setTransactions(prev => 
              prev.map(tx => 
                tx.hash === response.hash 
                  ? { ...tx, status: confirmed ? 'confirmed' : 'failed' }
                  : tx
              )
            );
          });

          // 添加延迟避免过快发送，让后端有时间处理
          await new Promise(resolve => setTimeout(resolve, 200));

        } catch (error) {
          console.error(`发送交易 ${i + 1} 失败:`, error);
          newTransactions.push({
            hash: `failed-${i}`,
            from: sender.address,
            to: receiver.address,
            value: txReq.value,
            status: 'failed',
            timestamp: Date.now(),
          });
          setTransactions([...newTransactions]);
        }
      }

      setStep('completed');
      
      // 更新全局nonce状态
      setNonceMap(localNonceMap);
      
      // 更新账户余额和批次信息
      updateAccountBalances();
      updateBatchInfo();

    } catch (error) {
      console.error('生成交易失败:', error);
      alert('生成交易失败，请检查控制台错误信息');
    } finally {
      setIsGenerating(false);
    }
  };

  // 更新账户余额
  const updateAccountBalances = async () => {
    const newBalances: AccountBalance[] = [];
    
    for (const account of accounts.slice(0, 10)) { // 只显示前10个账户
      try {
        const balanceResponse = await apiClient.getBalance(account.address);
        newBalances.push({
          address: account.address,
          balance: parseInt(balanceResponse.balance),
          nonce: 0, // 这里简化，实际应该从后端获取
        });
      } catch (error) {
        console.error(`获取账户 ${account.address} 余额失败:`, error);
        newBalances.push({
          address: account.address,
          balance: 0,
          nonce: 0,
        });
      }
    }
    
    setBalances(newBalances);
  };

  // 更新批次信息
  const updateBatchInfo = async () => {
    try {
      const blocksData = await apiClient.getAllBlocks();
      setBlocks(blocksData);
    } catch (error) {
      console.error('获取批次信息失败:', error);
    }
  };

  // 初始化所有账户的nonce状态
  const initializeNonceMap = async () => {
    if (!serverRunning || accounts.length === 0) return;
    
    const newNonceMap = new Map<string, number>();
    
    // 并行获取所有账户的nonce
    const noncePromises = accounts.map(async (account) => {
      try {
        const nonce = await apiClient.getNonce(account.address);
        return { address: account.address, nonce };
      } catch (error) {
        console.warn(`获取账户 ${account.address} nonce失败:`, error);
        return { address: account.address, nonce: 0 };
      }
    });
    
    const results = await Promise.all(noncePromises);
    results.forEach(({ address, nonce }) => {
      newNonceMap.set(address, nonce);
    });
    
    setNonceMap(newNonceMap);
    console.log('初始化nonce状态:', Object.fromEntries(newNonceMap));
  };

  useEffect(() => {
    // 组件挂载后初始化nonce状态
    initializeNonceMap();
  }, [serverRunning, accounts]);

  const confirmedCount = transactions.filter(tx => tx.status === 'confirmed').length;
  const pendingCount = transactions.filter(tx => tx.status === 'pending').length;
  const failedCount = transactions.filter(tx => tx.status === 'failed').length;

  return (
    <div className="min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
      <div className="fixed top-6 left-6 z-50 flex items-center bg-white rounded-full shadow border border-gray-200 px-2 h-10">
        <Link
          href="/"
          className="flex items-center justify-center px-2 h-8 rounded-full hover:bg-gray-100 text-base font-medium"
          aria-label="返回首页"
        >
          <svg width="24" height="24" fill="none" stroke="currentColor" strokeWidth="2" className="mr-1">
            <path d="M15 18l-6-6 6-6" />
          </svg>
          回到主页
        </Link>
        <span className="ml-4 text-2xl font-bold select-none">债券Rollup</span>
      </div>

      <main className="flex flex-col gap-8 items-center w-full max-w-5xl mx-auto pt-20">
        
        {/* 服务器状态 */}
        <div className="w-full bg-gray-50 rounded-lg p-6">
          <h2 className="text-xl font-semibold mb-4">系统状态</h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <span className="font-medium">服务器状态: </span>
              <span className={`inline-block w-3 h-3 rounded-full mr-2 ${serverRunning ? 'bg-green-500' : 'bg-red-500'}`}></span>
              <span className={serverRunning ? 'text-green-600' : 'text-red-600'}>
                {serverRunning === null ? '检查中...' : serverRunning ? '运行中' : '未运行'}
              </span>
            </div>
            <div>
              <span className="font-medium">状态根: </span>
              <span className="text-sm text-gray-600 font-mono">
                {stateRoot ? `${stateRoot.slice(0, 16)}...` : '获取中...'}
              </span>
            </div>
            <div>
              <span className="font-medium">Rollup批次: </span>
              <span className="text-blue-600 font-semibold">
                {blocks.length} 个批次
              </span>
            </div>
          </div>
        </div>

        {/* 交易配置 */}
        {step === 'setup' && (
          <div className="w-full bg-white rounded-lg p-6 border">
            <h2 className="text-xl font-semibold mb-4">批量交易配置</h2>
            <div className="flex items-center gap-4 mb-4">
              <label className="font-medium">交易数量:</label>
              <input
                type="number"
                value={transactionCount}
                onChange={(e) => setTransactionCount(Number(e.target.value))}
                min="1"
                max="1000"
                className="border rounded px-3 py-2 w-32"
              />
              <span className="text-sm text-gray-600">在30个账户之间随机生成</span>
            </div>
            
            <button
              onClick={generateTransactions}
              disabled={!serverRunning || isGenerating}
              className="bg-blue-600 text-white rounded px-6 py-2 hover:bg-blue-700 transition disabled:bg-gray-400"
            >
              {isGenerating ? '生成中...' : '开始生成交易'}
            </button>
          </div>
        )}

        {/* 交易进度 */}
        {step !== 'setup' && (
          <div className="w-full bg-white rounded-lg p-6 border">
            <h2 className="text-xl font-semibold mb-4">交易状态</h2>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
              <div className="text-center">
                <div className="text-2xl font-bold text-blue-600">{transactions.length}</div>
                <div className="text-sm text-gray-600">总交易数</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-green-600">{confirmedCount}</div>
                <div className="text-sm text-gray-600">已确认</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-yellow-600">{pendingCount}</div>
                <div className="text-sm text-gray-600">等待确认</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-red-600">{failedCount}</div>
                <div className="text-sm text-gray-600">失败</div>
              </div>
            </div>
            
            {step === 'generating' && (
              <div className="mb-4">
                <div className="bg-gray-200 rounded-full h-2">
                  <div 
                    className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                    style={{ width: `${(transactions.length / transactionCount) * 100}%` }}
                  ></div>
                </div>
                <div className="text-sm text-gray-600 mt-1">
                  已发送 {transactions.length} / {transactionCount} 笔交易
                </div>
              </div>
            )}

            {step === 'completed' && (
              <div className="mb-4">
                <button
                  onClick={async () => {
                    setStep('setup');
                    setTransactions([]);
                    // 重新初始化nonce状态
                    await initializeNonceMap();
                  }}
                  className="bg-gray-600 text-white rounded px-4 py-2 hover:bg-gray-700 transition mr-2"
                >
                  重新开始
                </button>
                <button
                  onClick={() => {
                    updateAccountBalances();
                    updateBatchInfo();
                  }}
                  className="bg-green-600 text-white rounded px-4 py-2 hover:bg-green-700 transition"
                >
                  刷新账户余额和批次信息
                </button>
              </div>
            )}
          </div>
        )}

        {/* 交易列表 */}
        {transactions.length > 0 && (
          <div className="w-full bg-white rounded-lg p-6 border">
            <h2 className="text-xl font-semibold mb-4">交易记录</h2>
            <div className="max-h-96 overflow-y-auto">
              <table className="w-full text-sm">
                <thead className="sticky top-0 bg-gray-100">
                  <tr>
                    <th className="border px-2 py-2">交易哈希</th>
                    <th className="border px-2 py-2">发送方</th>
                    <th className="border px-2 py-2">接收方</th>
                    <th className="border px-2 py-2">金额</th>
                    <th className="border px-2 py-2">状态</th>
                  </tr>
                </thead>
                <tbody>
                  {transactions.slice().reverse().map((tx) => (
                    <tr key={tx.hash}>
                      <td className="border px-2 py-1 font-mono text-xs">
                        {tx.hash.startsWith('failed-') ? tx.hash : `${tx.hash.slice(0, 12)}...`}
                      </td>
                      <td className="border px-2 py-1 font-mono text-xs">
                        ...{tx.from.slice(-8)}
                      </td>
                      <td className="border px-2 py-1 font-mono text-xs">
                        ...{tx.to.slice(-8)}
                      </td>
                      <td className="border px-2 py-1">{tx.value}</td>
                      <td className="border px-2 py-1">
                        <span className={`inline-block w-2 h-2 rounded-full mr-1 ${
                          tx.status === 'confirmed' ? 'bg-green-500' :
                          tx.status === 'pending' ? 'bg-yellow-500' : 'bg-red-500'
                        }`}></span>
                        {tx.status === 'confirmed' ? '已确认' :
                         tx.status === 'pending' ? '等待中' : '失败'}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* 账户余额 */}
        {balances.length > 0 && (
          <div className="w-full bg-white rounded-lg p-6 border">
            <h2 className="text-xl font-semibold mb-4">账户余额（前10个账户）</h2>
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-gray-100">
                  <th className="border px-4 py-2">账户地址</th>
                  <th className="border px-4 py-2">余额</th>
                </tr>
              </thead>
              <tbody>
                {balances.map((balance) => (
                  <tr key={balance.address}>
                    <td className="border px-4 py-2 font-mono text-xs">
                      {balance.address}
                    </td>
                    <td className="border px-4 py-2">{balance.balance}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* Rollup批次信息 */}
        {blocks.length > 0 && (
          <div className="w-full bg-white rounded-lg p-6 border">
            <h2 className="text-xl font-semibold mb-4">Rollup批次状态</h2>
            <div className="mb-4 text-sm text-gray-600">
              总共 {blocks.length} 个交易批次，每个批次包含多笔交易的汇总证明
            </div>
            
            <div className="max-h-96 overflow-y-auto">
              <div className="space-y-4">
                {blocks.slice().reverse().map((block) => (
                  <div key={block.hash} className="border rounded-lg p-4 bg-gray-50">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
                      <div>
                        <span className="font-medium text-blue-600">批次 #{block.height}</span>
                        <div className="text-xs text-gray-600 mt-1">
                          <div>批次哈希: {block.hash.slice(0, 16)}...</div>
                          <div>前批次哈希: {block.prevHash.slice(0, 16)}...</div>
                        </div>
                      </div>
                      <div>
                        <div className="text-sm">
                          <div>状态根: <span className="font-mono text-xs">{block.stateRoot.slice(0, 16)}...</span></div>
                          <div>Merkle根: <span className="font-mono text-xs">{block.merkleRoot.slice(0, 16)}...</span></div>
                          <div>交易数量: <span className="font-semibold text-green-600">{block.transactionCount}</span></div>
                          <div>提交时间: <span className="text-gray-600">{new Date(block.timestamp * 1000).toLocaleString()}</span></div>
                        </div>
                      </div>
                    </div>
                    
                    {block.transactions && block.transactions.length > 0 && (
                      <div>
                        <div className="font-medium text-sm mb-2 text-gray-700">批次内交易:</div>
                        <div className="max-h-32 overflow-y-auto">
                          <table className="w-full text-xs">
                            <thead className="bg-gray-200">
                              <tr>
                                <th className="border px-2 py-1">交易哈希</th>
                                <th className="border px-2 py-1">发送方</th>
                                <th className="border px-2 py-1">接收方</th>
                                <th className="border px-2 py-1">金额</th>
                                <th className="border px-2 py-1">状态</th>
                              </tr>
                            </thead>
                            <tbody>
                              {block.transactions.map((tx) => (
                                <tr key={tx.hash}>
                                  <td className="border px-2 py-1 font-mono">
                                    {tx.hash.slice(0, 12)}...
                                  </td>
                                  <td className="border px-2 py-1 font-mono">
                                    ...{tx.from.slice(-8)}
                                  </td>
                                  <td className="border px-2 py-1 font-mono">
                                    ...{tx.to.slice(-8)}
                                  </td>
                                  <td className="border px-2 py-1">{tx.value}</td>
                                  <td className="border px-2 py-1">
                                    <span className={`inline-block w-2 h-2 rounded-full mr-1 ${
                                      tx.status === 'confirmed' ? 'bg-green-500' : 'bg-yellow-500'
                                    }`}></span>
                                    {tx.status === 'confirmed' ? '已确认' : '等待中'}
                                  </td>
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        </div>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

      </main>
    </div>
  );
}
